import { zodResolver } from '@hookform/resolvers/zod'
import { Button, Dialog, DialogActions, DialogTitle, Grid } from '@mui/material'
import DialogContent from '@mui/material/DialogContent'
import { useMutation } from '@tanstack/react-query'
import { useCallback, useEffect, useState } from 'react'
import { type SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'

import { ConfirmationDialog } from '@/components/dialogs/confirmation.dialog'
import { TextFieldControlled } from '@/components/forms/TextFieldControlled'

import { type IAttachGroup, attachGroupFormScheme } from '@/types/attach.types'

import { attachService } from '@/services/attach.service'

export const AttachGroupDialog = ({
	group_data,
	open,
	onClose,
	createMode
}: {
	group_data: IAttachGroup
	open: boolean
	onClose: (group: IAttachGroup | undefined) => void
	createMode?: boolean
}) => {
	const [isOpened, setIsOpened] = useState(false)
	const [openConfDialog, setOpenConfDialog] = useState<boolean>(false)

	const handleClose = useCallback(
		(group: IAttachGroup | undefined) => {
			onClose(group)
			setIsOpened(false)
		},
		[onClose]
	)

	useEffect(() => setIsOpened(open), [open])

	const {
		formState: { isDirty, isValid },
		control,
		handleSubmit
	} = useForm<IAttachGroup>({
		mode: 'onChange',
		resolver: zodResolver(attachGroupFormScheme),
		defaultValues: group_data
	})

	const createGroup = useMutation({
		mutationKey: ['attach_group', 'create', group_data.id],
		mutationFn: (data: IAttachGroup) => attachService.createGroup(data),
		onSuccess: data => {
			toast.success('Группа успешно создана!')
			handleClose(data)
		},
		onError: () => toast.error('Ошибка создания группы')
	})

	const updateGroup = useMutation({
		mutationKey: ['attach_group', 'update', group_data.id],
		mutationFn: (data: IAttachGroup) => attachService.updateGroup(data),
		onSuccess: data => {
			toast.success('Группа успешно обновлена')
			handleClose(data)
		},
		onError: () => toast.error('Ошибка обновления группы')
	})

	const deleteGroup = useMutation({
		mutationKey: ['attach_group', 'delete', group_data.id],
		mutationFn: () => attachService.delGroup(group_data.id),
		onSuccess: () => {
			toast.success('Группа успешно удалена')
			handleClose(undefined)
		},
		onError: () => toast.error('Ошибка удаления группы')
	})

	const isPending =
		createGroup.isPending || updateGroup.isPending || deleteGroup.isPending

	const onSubmit: SubmitHandler<IAttachGroup> = data =>
		createMode ? createGroup.mutate(data) : updateGroup.mutate(data)

	return (
		<Dialog
			open={isOpened}
			onClose={() => handleClose(undefined)}
		>
			<DialogTitle>
				{createMode ? 'Создание группы' : 'Редактирование группы'}
			</DialogTitle>
			<DialogContent>
				<Grid
					container
					spacing={2}
					sx={{
						paddingTop: 2
					}}
				>
					<Grid
						item
						xs={12}
					>
						<TextFieldControlled
							control={control}
							name='name'
							label='Название'
						/>
					</Grid>

					<Grid
						item
						xs={12}
					>
						<TextFieldControlled
							control={control}
							name='description'
							label='Описание'
						/>
					</Grid>
				</Grid>
			</DialogContent>

			<DialogActions>
				{!createMode && (
					<>
						<ConfirmationDialog
							open={openConfDialog}
							title='Вы уверены, что хотите удалить ЭТУ ГРУППУ, все вложения находящиеся в этой группы будут переведены в несортированные'
							onConfirm={() => {
								deleteGroup.mutate()
								setOpenConfDialog(false)
							}}
							onClose={() => setOpenConfDialog(false)}
						/>
						<Button
							color='error'
							onClick={() => deleteGroup.mutate()}
							disabled={isPending}
						>
							Удалить
						</Button>
					</>
				)}
				<Button
					disabled={isPending || !isDirty || !isValid}
					color='success'
					onClick={handleSubmit(onSubmit)}
				>
					{isPending ? 'Сохранение...' : 'Сохранить'}
				</Button>
			</DialogActions>
		</Dialog>
	)
}
